// b2c/ddbj/ddbj.js
const md5 = require('../../js/md5.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _dzname:"",
    _dzphone:"",
    _dzaddress:"",
    mate:[],
    https:"https://csb2c.fenxiangqu.cn/",
    paytitle:"",
    ztdd:false,
    orderS:"",
    txfh:false,
    qxdd:false, 
    del:false,
    qd:false,
    zfdd:false,
    yhje:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  qd(res){
    wx.showModal({
      title: '提示',
      content: '确认订单已收货?',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: "https://csb2c.fenxiangqu.cn/xcx_zb_000022x_wx",
            data: {
              orderid: e.currentTarget.dataset.id
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Cookie': "LID=" + self.data.cookie
            },
            method: "POST",
            success: (data) => {
                wx.showToast({
                  title: '确认订单成功！',
                  icon: 'success',
                  duration: 2000
                })
              
                  wx.navigateBack()
              
            },
            fail(res) {
              wx.showToast({
                title: '网络请求失败',
                icon: 'success',
                duration: 1000
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  del(e){
    const self = this;
    wx.showModal({
      title: '提示',
      content: '是否删除订单?',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: "https://csb2c.fenxiangqu.cn/xcx_delete_order",
            data: {
              orderid: e.currentTarget.dataset.id
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Cookie': "LID=" + self.data.cookie
            },
            method: "POST",
            success: (ee) => {
              console.log(ee)
              if (ee.data == 0) {
                wx.showToast({
                  title: '删除订单失败',
                  icon: 'success',
                  duration: 2000
                })
              } else {
                if (ee.data == 1 || ee.data.ok == "1") {
                  wx.showToast({
                    title: '删除订单成功!',
                    icon: 'success',
                    duration: 2000
                  })
                  wx.navigateBack()
                }
              }
            },
            fail(res) {
              wx.showToast({
                title: '网络请求失败',
                icon: 'success',
                duration: 1000
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  onLoad: function (options) {
    const self = this;
    var a = wx.getStorageSync('cookie') || [];
    this.setData({
      cookie: a
    })
    wx.request({
      url: "https://csb2c.fenxiangqu.cn/xcx_order_unpaid",
      data: {
        oid: options.orderId
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'Cookie': "LID=" + self.data.cookie
      },
      method: "POST",
      success: (res) => {
        console.log(res)
        const json = res.data[0];
        let yhje = 0,yhq = 0,zl=0;
        for (let i = 0; i < json.goodsList.length;i++){
          zl += json.goodsList[i].weight;
        }

        if (json.ruleList.length > 0){
          for (let k = 0; k < json.ruleList.length; k++) {
            yhje += parseFloat(json.ruleList[k][2]);
            
          }
        }
        if (json.yhq_id == "") {

        } else {
          if (json.vouchersList.length){
            yhq = json.vouchersList[0]["yhq_count"];
          }else{
            yhq = 0
          }
          
        }
        var t = new Date(parseInt(json.creatTime));
        var tt = t.getFullYear() + "-" + (t.getMonth() + 1) + "-" + t.getDate() + " " + t.getHours() + ":" + t.getMinutes() + ":" + t.getSeconds();
        const k = (+yhq);
        self.setData({
          _dzname:json.consignee.name,
          _dzphone: json.consignee.phone,
          _dzaddress: json.consignee.prov + "" + json.consignee.city + "" + json.consignee.district + "" + json.consignee.address,
          mate: json.goodsList,
          paytitle: json["payType"],
          psfs: json.delivery_mode,
          ztdd: (json.delivery_mode == "自提" ? json.thd : false),
          fpxx: (json.consignee.fp ? json.consignee.fptt :"不需要发票信息"),
          orderS: json.orderState,
          all_price: parseFloat(json.paytotal).toFixed(2),
          yhj: k.toFixed(2),
          yhje: yhje.toFixed(2),
          kg:zl,
          yun_price: parseFloat(json.expressage.cost).toFixed(2),
          num: json.orderNum,
          time: tt
        })
        if(self.data.orderS == "已提交"){
          if (json.payState == "未支付" && json.payType != "货到付款"){
            self.setData({ orderS: self.data.orderS + ' ' + '等待买家付款,便宜不等人，赶紧支付吧!', qxdd: true, zfdd:true }); 
          }else{
            self.setData({ orderS: self.data.orderS + ' ' + '等待卖家处理,请耐心等待' });
          }
        } else if (self.data.orderS == "已受理"){
          self.setData({ orderS : '卖家已受理, 主人,请耐心等候发货!'});
          if (json.remind || json.remind == 1){
            self.setData({ orderS: '卖家已受理, 主人,请耐心等候发货!(已提醒发货)', txfh: false });
          }else{
            self.setData({ txfh: true });
          }
        } else if (self.data.orderS == "已发货"){
          self.data.orderS = "卖家已发货,主人，请耐心等候~";
          self.setData({ orderS: '卖家已发货,主人，请耐心等候~',qd:true });
        } else if (self.data.orderS == "已完成"){
          self.setData({ orderS: '订单已完成' });
        } else if (self.data.orderS == "已取消"){
          self.setData({ orderS: '订单已取消', del:true});
        } else if (self.data.orderS == "完成评价") {
            self.setData({ orderS: '完成评价!感谢您de支持，我们会做的更好~' });
        }
      }, 
      fail: (res) => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'success',
          duration: 1000
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },
  /*提醒发货 */
  txfh(e){
    const self = this;
    wx.showModal({
      title: '提示',
      content: '是否提醒发货?',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: "https://csb2c.fenxiangqu.cn/xcx_remind_shipments",
            data: {
              orderid: e.currentTarget.dataset.id
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Cookie': "LID=" + self.data.cookie
            },
            method: "POST",
            success: (data) => {
              console.log(data)
              if (data.data == 0){
                wx.showToast({
                  title: '提醒发货失败',
                  icon: 'success',
                  duration: 2000
                })
              }else{
                if (data.data.ok == "1") {
                  wx.showToast({
                    title: '提醒发货成功!',
                    icon: 'success',
                    duration: 2000
                  })
                  wx.navigateBack()
                }
              }
            },
            fail(res){
              wx.showToast({
                title: '网络请求失败',
                icon: 'success',
                duration: 1000
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /*取消发货 */
  qxdd(e){
    const self = this;
    wx.showModal({
      title: '提示',
      content: '确定取消订单吗?',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          wx.request({
            url: "https://csb2c.fenxiangqu.cn/xcx_cancel_order",
            data: {
              orderid: e.currentTarget.dataset.id
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Cookie': "LID=" + self.data.cookie
            },
            method: "POST",
            success: (data) => {
              console.log(data)
              if (data.data == 0) {
                wx.showToast({
                  title: '取消订单失败',
                  icon: 'success',
                  duration: 2000
                })
              } else {
                if (data.data.ok == "1") {
                  wx.showToast({
                    title: '取消订单成功!',
                    icon: 'success',
                    duration: 2000
                  })
                  wx.navigateBack()
                }
              }
            },
            fail(res) {
              wx.showToast({
                title: '网络请求失败',
                icon: 'success',
                duration: 1000
              })
            }
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  /*再支付 */
  zfdd(e){
    console.log('eee')
    const self = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: 'https://csb2c.fenxiangqu.cn/xcxonLogin',
            data: {
              code: res.code
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded',
              'Cookie': "LID=" + self.data.cookie
            },
            method: "POST",
            success(res) {
              const openid = res.data;
              console.log(openid)
              wx.request({
                url: "https://csb2c.fenxiangqu.cn/xcx_again_payment",
                data: {
                  oid: e.currentTarget.dataset.id,
                  je: e.currentTarget.dataset.all_price,
                  openid: openid.openid
                },
                header: {
                  'content-type': 'application/x-www-form-urlencoded',
                  'Cookie': "LID=" + self.data.cookie
                },
                method: "POST",
                success: (data) => {
                  console.log(data)
                  if (data.data == 0) {
                    wx.showToast({
                      title: '取消订单失败',
                      icon: 'success',
                      duration: 2000
                    })
                    wx.navigateBack()
                  } else {
                    const json = data.data;
                    if(json.ret == "wx"){
                      wx.request({
                        url: 'https://csb2c.fenxiangqu.cn/xcx_pay',
                        data: {
                          orderid: e.currentTarget.dataset.id,
                          openid: openid,
                          price: e.currentTarget.dataset.num
                        },
                        method: "POST",
                        header: {
                          'content-type': 'application/json',
                          'Cookie': "LID=" + self.data.cookie // 默认值
                        },
                        success: function (pay) {
                          const appId = pay.data.appId, timeStamp = (Date.parse(new Date()) / 1000).toString(),
                            pkg = Math.random().toString(36).substr(2), id = pay.data.package;
                          wx.requestPayment({
                            appId: appId,
                            timeStamp: timeStamp,
                            nonceStr: pkg,
                            "package": "" + id + "",
                            signType: "MD5",
                            paySign: md5.hexMD5('appId=' + appId + '&nonceStr=' + pkg + '&package=' + id + '&signType=MD5&timeStamp=' + timeStamp + "&key=SYHLKJSYHLKJSYHLKJSYHLKJSYHLKJ00").toUpperCase(),
                            success(res) {
                              if (res.errMsg == "requestPayment:ok") {
                                wx.showToast({
                                  title: '支付成功!',
                                  icon: 'success',
                                  duration: 3000
                                })
                                wx.switchTab({
                                  url: '../home/home',
                                })
                              } else {
                                wx.showToast({
                                  title: '支付失败!',
                                  icon: 'success',
                                  duration: 3000
                                })
                                wx.switchTab({
                                  url: '../center/center',
                                })
                              }
                            },
                            fail(res) {
                              wx.showToast({
                                title: '下单失败!',
                                icon: 'success',
                                duration: 3000
                              })
                              wx.switchTab({
                                url: '../center/center',
                              })
                            }
                          })
                        },
                        fail: function (res) {
                          wx.showToast({
                            title: '网络请求失败',
                            icon: 'success',
                            duration: 1000
                          })
                        }
                      })
                    }else if(json.ret == "no_money"){
                      wx.showToast({
                        title: '余额不足不足',
                        icon: 'success',
                        duration: 2000
                      })
                      wx.navigateBack()
                    } else if (json.ret == "err") {
                      wx.showToast({
                        title: '支付异常002',
                        icon: 'success',
                        duration: 2000
                      })
                      wx.navigateBack()
                    } else if (json.ret == "no_openid") {
                      wx.showToast({
                        title: '支付异常003',
                        icon: 'success',
                        duration: 2000
                      })
                      wx.navigateBack()
                    }
                    
                  }
                },
                fail(res) {
                  wx.showToast({
                    title: '网络请求失败',
                    icon: 'success',
                    duration: 1000
                  })
                }
              })
            },
            fail(res) {
              console.log(res)
            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
    
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
  
  }
})